import 'dart:convert';
import 'package:basic_common/common_exports.dart';
import 'package:basic_common/global_getx.dart';
import 'package:basic_profile/model/activa_code_data.dart';
import 'package:basic_profile/model/cer_result_data.dart';
import 'package:flutter/services.dart';

class SettingController extends GetxController {
  // 与Android通信 通道
  MethodChannel methodChannel = MethodChannel("com.hnxyj.fwapp/plugin");

  /// 与原生Android互传数据
  static const basicMessageChannel = BasicMessageChannel(
      "com.hnxyj.fwapp/plugin/data", StandardMessageCodec());

  GlobalGetx mainTabController = Get.find<GlobalGetx>();

  /// 签名登录 获取账号列表
  getAccountList() async {
    //传递数据给android原生
    try {
      int cerLen = await methodChannel.invokeMethod(
          "resetUserListData", "getAccountListData");
      // if (cerLen == 0) {
      getActivaCode();
      // }
    } on PlatformException catch (error) {
      return error.stacktrace!;
    }
  }

  /// 将激活码传入移动端SDK
  sendActivaCodeToSdk(String code) async {
    try {
      String jsonRes = await methodChannel.invokeMethod("getActivaCode", code);
      if (jsonRes.isNotEmpty) {
        CerResultData resultData = CerResultData.fromJson(jsonDecode(jsonRes));
        if (resultData.status == "success") {
          // ToastUtils.toast("证书下载成功，快去登录吧");
          // Get.back();
        }
      }
    } on PlatformException catch (error) {
      return error.stacktrace!;
    }
  }

  // 监听Android发送来的签名信息
  void _listenMessageFromNative() {
    //Flutter接收Native发来的消息
    basicMessageChannel.setMessageHandler((message) {
      // signInfo.value = message!.toString();
      String res = message.toString();
      if (res.isEmpty) {
        ToastUtils.toast("下载证书信息不能为空");
        return Future.value("下载证书信息不能为空");
      }
      CerResultData cerResultData =
          CerResultData.fromJson(jsonDecode(message.toString()));
      if (cerResultData.status == "success") {
        ToastUtils.toast("申请证书成功");
      } else {
        ToastUtils.toast("申请证书失败");
      }
      return Future.value(message.toString());
    });
  }

  // 获取激活码
  getActivaCode() async {
    HttpData res =
        await ApiService().getActivaCode(data: {"searchKey": "Token"});
    if (res.code == 1) {}
    ActivaCodeData activaData = ActivaCodeData.fromJson(res.data);
    if (activaData.status == 200) {
      String code = activaData.data!.authCode!;
      sendActivaCodeToSdk(code);
    }
  }

  /// 检测版本 更新
  void updateNewVer() {
    mainTabController.getUpdate(2);
  }

  @override
  void onInit() async {
    // TODO: implement onInit
    super.onInit();
    _listenMessageFromNative();
  }
}
